package com.example.Dao;

import com.example.pojo.Comment;
import com.example.pojo.News;
import com.example.utils.ConnUtils;
import com.example.utils.DataUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    //管理员角度
    //统计总行数
    public int getTotalByNewsId(int id){
        int flag =0;
        Connection conn =ConnUtils.getConn();
        //编写SQL
        String sql ="select count(*) from comment where newsId=?";
        try {
            PreparedStatement pst =conn.prepareStatement(sql);
            pst.setInt(1,id);
            ResultSet rs = pst.executeQuery();
            if (rs.next()){
                flag = rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DataUtils.closeConnection(conn);
        }
        return flag;
    }

public int addComment(Comment comment) {
    int flag = 0;
    Connection conn = null;
    PreparedStatement pst = null;
    try {
        conn = DataUtils.getConn();
        // 修复表名：news → comment，字段名对应 comment 表
        String sql = "INSERT INTO comment (userId, newsId, commentContent, commentDate, likeNum) " +
                "VALUES (?, ?, ?, SYSDATE(), ?)";
        pst = conn.prepareStatement(sql);
        pst.setString(1, comment.getUserId());
        pst.setInt(2, comment.getNewsId());
        pst.setString(3, comment.getCommentContent());
        pst.setInt(4, comment.getLikeNum());
        flag = pst.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("添加评论失败", e);
    } finally {
//        DataUtils.closePreparedStatement(pst);
        DataUtils.closeConnection(conn);
    }
    return flag;
}
    public int addLikeComment(int commentId, String userId) { // 移除 count 参数，固定增减逻辑
        Connection conn = null;
        PreparedStatement pst = null;
        PreparedStatement pstUserLike = null;
        try {
            conn = DataUtils.getConn();
            conn.setAutoCommit(false); // 关闭自动提交，开启事务

            int likeChange = 1; // 默认：点赞（+1）
            String sqlUserLike;

            // 1. 判断是否已点赞，决定新增/删除关联记录
            if (findIslike(commentId, userId) > 0) {
                // 已点赞 → 取消点赞：删除关联记录，点赞数-1
                sqlUserLike = "DELETE FROM user_comment_like WHERE user_id=? AND comment_id=?";
                likeChange = -1;
            } else {
                // 未点赞 → 点赞：新增关联记录，点赞数+1
                sqlUserLike = "INSERT INTO user_comment_like (user_id, comment_id) VALUES (?, ?)";
            }

            // 执行 user_comment_like 操作
            pstUserLike = conn.prepareStatement(sqlUserLike);
            pstUserLike.setString(1, userId);
            pstUserLike.setInt(2, commentId);
            pstUserLike.executeUpdate();

            // 2. 更新 comment 表的 likeNum
            String sqlComment = "UPDATE comment SET likeNum = likeNum + ? WHERE commentId=?";
            pst = conn.prepareStatement(sqlComment);
            pst.setInt(1, likeChange);
            pst.setInt(2, commentId);
            int affectedRows = pst.executeUpdate();

            conn.commit(); // 所有操作成功，提交事务
            return affectedRows; // 返回点赞数更新的受影响行数（1 表示成功）
        } catch (SQLException e) {
            // 发生异常，回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    throw new RuntimeException("事务回滚失败", ex);
                }
            }
            throw new RuntimeException("点赞操作失败", e);
        } finally {
            // 关闭所有资源

            DataUtils.closeConnection(conn);
        }
    }
    public int deleteComment(int commentId) { // 参数名改为 commentId，更清晰
        int flag = 0;
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            conn = DataUtils.getConn();
            String sql = "DELETE FROM comment WHERE commentId=?"; // 修复表名和字段名
            pst = conn.prepareStatement(sql);
            pst.setInt(1, commentId);
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除评论失败", e);
        } finally {
//            DataUtils.closePreparedStatement(pst);
            DataUtils.closeConnection(conn);
        }
        return flag;
    }
    public int findIslike(int commentId, String userId) {
        int count = 0;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = DataUtils.getConn();
            String sql = "SELECT COUNT(*) FROM user_comment_like WHERE comment_id=? AND user_id=?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, commentId);
            pst.setString(2, userId);
            rs = pst.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询点赞状态失败", e);
        } finally {
//            DataUtils.closeResultSet(rs);
//            DataUtils.closePreparedStatement(pst);
            DataUtils.closeConnection(conn);
        }
        return count;
    }
    public  int deleteBatchNews(List<Integer> ids){
        int flag=0;
        //关掉自动提交
        Connection conn = DataUtils.getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String sql = "delete from news where newsId in ";
        try {
            StringBuilder sb =new StringBuilder();
            for (int i = 0; i < ids.size(); i++) {
                if (i==0){
                    sb.append("(");
                }
                sb.append("?");
                if (i<ids.size()-1){
                    sb.append(",");
                }
                if (i==ids.size()-1){
                    sb.append(")");

                }
            }
            sql +=sb.toString();
            PreparedStatement pst =conn.prepareStatement(sql);
            for (int i = 0; i <ids.size() ; i++) {
                pst.setInt(i+1,ids.get(i));
            }
            System.out.println(sql);
            flag = pst.executeUpdate();
            if (flag>0){
                conn.commit();
            }
        }catch (Exception e){
            //回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }finally {
            DataUtils.closeConnection(conn);
        }
        return flag;
    }
    public List<Comment> getCommentByNewsId(int newsId, String userId) {
        List<Comment> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = DataUtils.getConn();
            String sql = "SELECT c.*, " +
                    "(SELECT COUNT(*) FROM user_comment_like ucl WHERE ucl.comment_id = c.commentId AND ucl.user_id = ?) > 0 AS isLiked " +
                    "FROM comment c WHERE c.newsId=? ORDER BY likeNum DESC ";
            pst = conn.prepareStatement(sql);
            pst.setString(1, userId);
            pst.setInt(2, newsId);
            rs = pst.executeQuery();
            while (rs.next()) {
                Comment comment = new Comment(
                        rs.getInt("commentId"),
                        rs.getString("userId"),
                        rs.getInt("newsId"), // 补全：给 newsId 赋值
                        rs.getString("commentContent"),
                        rs.getString("commentDate"),
                        rs.getInt("likeNum"),
                        rs.getBoolean("isLiked")
                );
                list.add(comment);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询评论列表失败", e);
        } finally {
//            DataUtils.closeResultSet(rs);
//            DataUtils.closePreparedStatement(pst);
            DataUtils.closeConnection(conn);
        }
        return list;
    }

    public Comment getCommentById(int commentId) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        Comment comment = null;
        try {
            conn = DataUtils.getConn();
            String sql = "SELECT * FROM comment WHERE commentId=?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, commentId);
            rs = pst.executeQuery();
            if (rs.next()) {
                comment = new Comment(
                        rs.getInt("commentId"),
                        rs.getString("username"),
                        rs.getInt("newsId"), // 补全：给 newsId 赋值
                        rs.getString("commentContent"),
                        rs.getString("commentDate"),
                        rs.getInt("likeNum")
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询评论详情失败", e);
        } finally {
//            DataUtils.closeResultSet(rs);
//            DataUtils.closePreparedStatement(pst);
            DataUtils.closeConnection(conn);
        }
        return comment;
    }



}
